import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.Formatter;
import java.util.Scanner;

public class StationDataDemo {

    private static final String API_KEY = "dZ-XEIUwxNVa3IE2_65bnPhL_-5ONzb-FxEBfuCPaZE";
    private static final String API_SECRET = "B3QfeDPCqt532BFHYLCUjZZcZtztWmWzdyCgMefVYYx90JRTTwHfGKv9qrSNdsRFTWJQD6QQksdMN9uJnwJcOw";

    public static void main(String[] args) {
        try {
            // 生成当前时间戳
            String timestamp = String.valueOf(Instant.now().getEpochSecond());

            // 创建签名
            String signature = createSignature(API_KEY, API_SECRET, timestamp);

            // 指定小时内的数据，1<= hours <=6，默认3
            int hours = 3;

            // 带有查询参数的URL
            String urlString = String.format("http://36.137.227.217:8000/tn/station-data?hours=%d&api_key=%s&timestamp=%s&signature=%s",
                    hours, API_KEY, timestamp, signature);

            // 发送GET请求
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 打印响应
            int responseCode = connection.getResponseCode();
            System.out.println("URL: " + urlString);
            System.out.println("响应状态码: " + responseCode);

            Scanner scanner = new Scanner(connection.getInputStream());
            while (scanner.hasNext()) {
                System.out.println(scanner.nextLine());
            }
            scanner.close();

        } catch (IOException | NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
    }

    private static String createSignature(String apiKey, String apiSecret, String timestamp)
            throws NoSuchAlgorithmException, InvalidKeyException {
        String message = apiKey + apiSecret + timestamp;
        Mac sha256Hmac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        sha256Hmac.init(secretKey);
        return toHexString(sha256Hmac.doFinal(message.getBytes(StandardCharsets.UTF_8)));
    }

    private static String toHexString(byte[] bytes) {
        Formatter formatter = new Formatter();
        for (byte b : bytes) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    }

}
